package com.example.orderminiappapi.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.example.orderminiappapi.bean.*;
import com.example.orderminiappapi.service.UserAddressService;
import com.example.orderminiappapi.service.UserRemarksService;
import com.example.orderminiappapi.service.UserService;
import com.example.orderminiappapi.tool.HttpRequestUril;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

@RestController
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private UserRemarksService userRemarksService;


    /**
     * 用户登录的时候获取其openid，再根据其openid从数据库中找到该用户，并为其此次登录赋予token
     */
    @ResponseBody
    @RequestMapping(value = "/getOpenid", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getOpenid(@RequestBody User user) throws JsonProcessingException {

        String appid = "wxe555209e9910c983";
        String secret = "d5444133b8e1aa1f946ad786d02aa3c7";
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid +
                "&secret=" + secret + "&js_code="  + user.getCode() +  "&grant_type=authorization_code";

        System.out.println(url);

        String data = HttpRequestUril.sendGet(url, "");

        ObjectMapper mapper = new ObjectMapper();
        User user1 = mapper.readValue(data, User.class);

        Boolean flag = true; // 用于判断用户是否是第一次登录

        User user2 = userService.findAllUser(user1);
        if(user2 == null) {
            userService.addNewUser(user1);
            flag = false;
        } else {
            if(user2.getUserName() == null) {
                flag = false;
            }
        }

        System.out.println("Data");
        System.out.println(user1);

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 1);

        String token = JWT.create().withHeader(new HashMap<>())
                .withClaim("openId", user1.getOpenid())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256("userInfo"));
        System.out.println("token = " + token);

        Response response = new Response("10000", flag ? "成功" : "验证", token);

        return response;
    }

    /**
     * 如果用户是第一次登录，需要向微信发送请求获取其微信的个人信息
     */
    @ResponseBody
    @RequestMapping(value = "/perfectUserInfo", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response perfectUserInfo(HttpServletRequest request, @RequestBody User user) throws JsonProcessingException {


        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String userId = verify.getClaim("openId").asString();
        user.setUserId(userId);

        int flag = userService.perfectUserInfo(user);

        Response response;

        if(flag == 1) {
            response = new Response("10000", "成功", "成功");
        } else {
            response = new Response("10010", "修改失败", "修改失败");
        }

        return response;
    };

    /**
     * 当用户访问个人主页时，获取其个人信息
     */
    @ResponseBody
    @RequestMapping(value = "/getOneUserInfo", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getOneUserInfo(HttpServletRequest request) throws JsonProcessingException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String userId = verify.getClaim("openId").asString();

        User user = new User();
        user.setOpenid(userId);

        User nowUser = userService.findAllUser(user);

        nowUser.setAddress(userAddressService.findAllUsersAddress(user));
        nowUser.setRemarks(userRemarksService.findAllUsersRemarks(user));

        System.out.println(nowUser);

        Response response;

        if (nowUser != null) {
            response = new Response("10000", "成功", nowUser);
        } else {
            response = new Response("10010", "未查找到该用户", "未查找到该用户");
        }

        return response;
    };

    /**
     * 用户修改其真实姓名
     */
    @ResponseBody
    @RequestMapping(value = "/doChangeRealName", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response doChangeRealName(HttpServletRequest request, @RequestBody AddOrUpdate addOrUpdate) throws JsonProcessingException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String userId = verify.getClaim("openId").asString();

        addOrUpdate.setId(userId);

        int flag = userService.changeRealName(addOrUpdate);

        Response response;


        if (flag == 1) {
            response = new Response("10000", "成功", "成功");
        } else {
            response = new Response("10010", "失败", "失败");
        }


        return response;
    };

    /**
     * 用户修改其性别
     */
    @ResponseBody
    @RequestMapping(value = "/doChangeSex", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response doChangeSex(HttpServletRequest request, @RequestBody AddOrUpdate addOrUpdate) throws JsonProcessingException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String userId = verify.getClaim("openId").asString();

        addOrUpdate.setId(userId);

        int flag = userService.changeSex(addOrUpdate);

        Response response;


        if (flag == 1) {
            response = new Response("10000", "成功", "成功");
        } else {
            response = new Response("10010", "失败", "失败");
        }


        return response;
    };

    /**
     * 用户修改其真实姓名
     */
    @ResponseBody
    @RequestMapping(value = "/doChangePhone", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response doChangePhone(HttpServletRequest request, @RequestBody AddOrUpdate addOrUpdate) throws JsonProcessingException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String userId = verify.getClaim("openId").asString();

        addOrUpdate.setId(userId);

        int flag = userService.changePhone(addOrUpdate);

        Response response;


        if (flag == 1) {
            response = new Response("10000", "成功", "成功");
        } else {
            response = new Response("10010", "失败", "失败");
        }


        return response;
    };



    /**
     * 后台管理接口
     */

    /**
     * 注册新店主
     */
    @ResponseBody
    @RequestMapping(value = "/addNewShopOwner", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response addNewShopOwner(@RequestBody User user) throws JsonProcessingException {

        User returnUser = userService.findShopOwner(user);

        Response response;

        if(returnUser != null){
            response = new Response("10011", "该账号已被注册", "该账号已被注册");
        } else {
            int flag = userService.addNewShopOwner(user);

            response = new Response(flag == 1 ? "10000" : "10010", flag == 1 ? "成功" : "失败", flag == 1 ? "成功" : "失败");
        }

        return response;
    }

    /**
     * 注册新店主
     */
    @ResponseBody
    @RequestMapping(value = "/signIn", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response signIn(@RequestBody User user) {

        User returnUser = userService.signIn(user);

        Response response;

        if(returnUser == null){
            response = new Response("10011", "账号或密码错误", "该账号已被注册");
        } else {

            Calendar instance = Calendar.getInstance();
            instance.add(Calendar.DATE, 1);

            String token = JWT.create().withHeader(new HashMap<>())
                    .withClaim("userId", returnUser.getUserId())
                    .withExpiresAt(instance.getTime())
                    .sign(Algorithm.HMAC256("userInfo"));
            System.out.println("token = " + token);
            returnUser.setToken(token);

            response = new Response("10000", "成功" , returnUser);
        }

        return response;
    }

    /**
     * 在token中添加shopId
     */
    @ResponseBody
    @RequestMapping(value = "/changeNowShopToken", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response changeNowShopToken(HttpServletRequest request, @RequestBody Request requests) throws JsonProcessingException {

        String token = request.getHeader("tokenMiniAPP");

        JWTVerifier build = JWT.require(Algorithm.HMAC256("userInfo")).build();
        DecodedJWT verify = build.verify(token);

        String userId = verify.getClaim("userId").asString();

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 1);

        String thisToken = JWT.create().withHeader(new HashMap<>())
                .withClaim("userId", userId)
                .withClaim("shopId", requests.getKeywords())
                .withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256("userInfo"));

        System.out.println("thisToken=" + thisToken);

        Response response = new Response("10000", "成功", thisToken);
        return response;
    }

    /**
     * 获取单个user的全部信息
     */
    @ResponseBody
    @RequestMapping(value = "/managerGetOneUserInfo", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response managerGetOneUserInfo(@RequestBody User user) throws JsonProcessingException {

        User user1 = userService.findShopOwner(user);

        Response response = new Response("10000", "成功", user1);
        return response;
    }

    /**
     * 获取单个user的全部信息
     */
    @ResponseBody
    @RequestMapping(value = "/getAllUsers", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response getAllUsers(@RequestBody SearchCondition searchCondition) {

        searchCondition.setData(userService.getAllUsers(searchCondition));
        searchCondition.setTotal(userService.getAllUsersCount(searchCondition));

        Response response = new Response("10000", "成功", searchCondition);

        return response;
    }

    /**
     * 管理员修改单个user的信息
     */
    @ResponseBody
    @RequestMapping(value = "/managerUpdateUserInfo", method = RequestMethod.POST,produces = "application/json;charset=UTF-8")
    private Response managerUpdateUserInfo(@RequestBody User user) {

        userService.managerUpdateUserInfo(user);

        Response response = new Response("10000", "成功", "成功");

        return response;
    }
}
